package tk.sunlatus.game.sudo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @{# SudoStack.java Create on Apr 2, 2012 10:55:48 AM
 * 
 *     类功能说明: 数独解码需要回溯时，保存位置信息
 * 
 *     <p>
 *     Copyright: Copyright(c) 2012
 *     </p>
 * @Version 1.0
 * @Author 悠忧虫
 */
public class SudoStack {

    private List<Location> values = null;

    private boolean initFlag = false;

    private synchronized void init() {
        if (values == null) {
            values = new ArrayList<Location>();
        }
        initFlag = true;
    }

    /**
     * 方法描述:出栈
     * 
     * @return
     */
    public synchronized Location pop() {
        // System.out.println("stack info :" + values);
        if (!initFlag || values.isEmpty()) {
            return null;
        }
        // System.out.println("pop:" + values.get(values.size() - 1));
        return values.remove(values.size() - 1);
    }

    /**
     * 方法描述：将数独位置入栈
     * 
     * @param location
     */
    public synchronized void push(Location location) {
        if (!initFlag) {
            init();
        }
        values.add(location);
        // System.out.println("push:" + values.get(values.size() - 1));
    }

    /**
     * 方法描述：清理栈中数据
     */
    public void clear() {
        if (!initFlag) {
            return;
        }
        values.clear();
        values = null;
        initFlag = false;
    }
}

/**
 * 类功能说明:数独位置信息
 * 
 * <p>
 * Copyright: Copyright(c) 2012
 * </p>
 * 
 * @Version 1.0
 * @Author 悠忧虫
 */
class Location {
    private int x = 1;
    private int y = 1;
    private List<Integer> values = new ArrayList<Integer>();

    public Location() {
    }

    public Location(int x, int y, Collection<Integer> values) {
        this.x = x;
        this.y = y;
        this.values.clear();
        this.values.addAll(values);
    }

    Integer nextValue() {
        if (values.isEmpty()) {
            return 0;
        }
        return values.remove(0);
    }

    Integer getValue() {
        if (values.isEmpty()) {
            return 0;
        }
        return values.get(0);
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public void setValues(List<Integer> values) {
        this.values.clear();
        this.values.addAll(values);
    }

    public List<Integer> getValues() {
        return values;
    }

    public String toString() {
        return "location:[" + x + "," + y + "]=" + Arrays.toString(values.toArray());
    }
}
